/**
 * @description  : 移动平台的 钉钉api适配
 * @descriptionDetail : 移动平台的api适配
 * @copyright    : 浙江烟草
 * @author       : mc
 * @create       : 2022-09-04 19:31:34
 */
import * as EXIF from 'exif-js';
import {
	isDD,
} from "../common/util";
import {
	DD_MODEL,
} from "@/config/setting.config.js";

let DingDing = {
	/**
	 * 是否显示顶部的自定义导航栏  并不当做顶部导航栏是否显示，只是用作代码中的配套
	 * @returns
	 */
	isHideNav: () => {
		return isDD();
	},
	/**
	 * 钉钉toast弹窗
	 */
	toast: (str) => {
		// DD_MODEL == 0 专属钉
		if (DD_MODEL == 0) {
			dd.device.notification.toast({
				text: str, // 提示信息
				onSuccess: function(result) {},
				onFail: function(err) {},
			});
		} else if (DD_MODEL == 1) {
			sinoware.device.notification.toast({
				text: str, // 提示信息
				onSuccess: function(result) {},
				onFail: function(err) {},
			});
		}
	},
	/**
	 * 钉钉提示
	 * @param {*} msg     提示信息
	 * @param {*} title   标题(可选)
	 */
	alert: (msg, title, success) => {
		// DD_MODEL == 0 专属钉
		if (DD_MODEL == 0) {
			dd.device.notification.alert({
				message: msg,
				title: title || "提示",
				buttonName: "确定",
				onSuccess: function() {
					// onSuccess将在点击button之后回调
					/* 回调*/
					success();
				},
				onFail: function(err) {},
			});
		} else if (DD_MODEL == 1) {
			sinoware.device.notification.alert({
				message: msg,
				title: title || "提示",
				buttonName: "确定",
				onSuccess: function() {
					/* 回调*/
					success();
				},
				onFail: function(err) {},
			});
		}
	},
	/**
	 * 钉钉确认框
	 */
	confirm: (msg, title, btns, success) => {
		// 专属钉
		if (DD_MODEL == 0) {
			dd.device.notification.confirm({
				message: msg,
				title: title,
				buttonLabels: btns,
				onSuccess: function(result) {
					success(result.buttonIndex);
				},
				onFail: function(err) {},
			});
		} else if (DD_MODEL == 1) {
			sinoware.device.notification.confirm({
				message: msg,
				title: title,
				buttonLabels: btns,
				onSuccess: function(result) {
					success(result.buttonIndex);
				},
				onFail: function(err) {},
			});
		}
	},
	// 开始录音
	startRecord: () => {
		return new Promise(function(resolve, reject) {
			// 专属钉
			if (DD_MODEL == 0) {
				dd.device.audio.startRecord({
					maxDuration: 300, // 支持最长为300秒（包括）的音频录制，默认60秒(包括)。
					onSuccess: () => resolve(),
					onFail: err => reject(err),
				});
			} else if (DD_MODEL == 1) {
				sinoware.device.audio.startRecord({
					maxDuration: 300, // 支持最长为300秒（包括）的音频录制，默认60秒(包括)。
					onSuccess: () => resolve(),
					onFail: err => reject(err),
				});
			}
		});
	},
	// 停止录音
	stopRecord: () => {
		return new Promise(function(resolve, reject) {
			// 专属钉
			if (DD_MODEL == 0) {
				dd.device.audio.stopRecord({
					// res.mediaId; // 返回音频的MediaID，可用于本地播放和音频下载
					// res.duration; // 返回音频的时长，单位：秒
					onSuccess: res => resolve(res),
					onFail: err => reject(err),
				});
			} else if (DD_MODEL == 1) {
				sinoware.device.audio.stopRecord({
					// res.mediaId; // 返回音频的MediaID，可用于本地播放和音频下载
					// res.duration; // 返回音频的时长，单位：秒
					onSuccess: res => resolve(res),
					onFail: err => reject(err),
				});
			}
		});
	},
	// 监听录音自动停止
	onRecordEnd: () => {
		return new Promise(function(resolve, reject) {
			// 专属钉
			if (DD_MODEL == 0) {
				dd.device.audio.onRecordEnd({
					// res.mediaId; // 停止播放音频MediaID
					// res.duration; // 返回音频的时长，单位：秒
					onSuccess: res => resolve(res),
					onFail: err => reject(err),
				});
			} else if (DD_MODEL == 1) {
				sinoware.device.audio.onRecordEnd({
					// res.mediaId; // 停止播放音频MediaID
					// res.duration; // 返回音频的时长，单位：秒
					onSuccess: res => resolve(res),
					onFail: err => reject(err),
				});
			}
		});
	},
	// 下载音频
	downlaod: (mediaId) => {
		return new Promise(function(resolve, reject) {
			// 专属钉
			if (DD_MODEL == 0) {
				dd.device.audio.download({
					mediaId: mediaId,
					onSuccess: res => resolve(res.localAudioId),
					onFail: err => reject(err),
				});
			} else if (DD_MODEL == 1) {
				sinoware.device.audio.download({
					mediaId: mediaId,
					onSuccess: res => resolve(res.localAudioId),
					onFail: err => reject(err),
				});
			}
		});
	},
	// 播放语音
	play: (localAudioId) => {
		return new Promise(function(resolve, reject) {
			// 专属钉
			if (DD_MODEL == 0) {
				dd.device.audio.play({
					localAudioId: localAudioId,
					onSuccess: result => resolve(result),
					onFail: err => reject(err),
				});
			} else if (DD_MODEL == 1) {
				sinoware.device.audio.play({
					localAudioId: localAudioId,
					onSuccess: result => resolve(result),
					onFail: err => reject(err),
				});
			}
		});
	},
	// 图片预览
	previewImage: (urls, current) => {
		return new Promise(function(resolve, reject) {
			if (DD_MODEL == 0) {
				dd.biz.util.previewImage({
					urls: urls, // 图片地址列表
					current: current, // 当前显示的图片链接
					onSuccess: result => resolve(result),
					onFail: err => reject(err),
				});
			} else if (DD_MODEL == 1) {
				sinoware.biz.util.previewImage({
					urls: urls, // 图片地址列表
					current: current, // 当前显示的图片链接
					onSuccess: result => resolve(result),
					onFail: err => reject(err),
				});
			}
		});
	},
	// 设置标题
	setTitle: (title) => {
		// 专属钉
		if (DD_MODEL == 0) {
			dd.biz.navigation.setTitle({
				title: title, // 控制标题文本，空字符串表示显示默认文本
				onSuccess: result => console.log(result),
				onFail: err => console.error(err),
			});
		} else if (DD_MODEL == 1) {
			sinoware.biz.navigation.setTitle({
				title: title, // 控制标题文本，空字符串表示显示默认文本
				onSuccess: result => console.log(result),
				onFail: err => console.error(err),
			});
		}
	},
	// 设置右侧单个按钮
	setRight: (text, cb, control, isShow) => {
		// 专属钉
		if (DD_MODEL == 0) {
			dd.biz.navigation.setRight({
				show: typeof isShow === 'undefined' ? true :
				isShow, // 控制按钮显示， true 显示， false 隐藏， 默认true
				control: typeof control === 'undefined' ? true :
				control, // 是否控制点击事件，true 控制，false 不控制， 默认false
				text: text, // 控制显示文本，空字符串表示显示默认文本
				onSuccess: result => cb && cb(result),
				onFail: err => console.error(err),
			});
		} else if (DD_MODEL == 1) {
			sinoware.biz.navigation.setRight({
				show: typeof isShow === 'undefined' ? true :
				isShow, // 控制按钮显示， true 显示， false 隐藏， 默认true
				control: typeof control === 'undefined' ? true :
				control, // 是否控制点击事件，true 控制，false 不控制， 默认false
				text: text, // 控制显示文本，空字符串表示显示默认文本
				onSuccess: result => cb && cb(result),
				onFail: err => console.error(err),
			});
		}
	},
	/**
	 * 设置导航栏右侧多个按钮(针对不同的点击处理不同的内容)
	 * 苹果手机对此接口的格式要求比较严格，不能出现多余的符号！！！
	 * @param {*} items '[{"id": "1", "text": "刷新"},{"id": "2", "text": "更多"}]'
	 * @param {*} cb 点击后的回调函数
	 * @param {*} backgroundColor
	 * @param {*} textColor
	 * @returns
	 */
	setMenu: (items, cb, backgroundColor, textColor) => {
		// 专属钉
		if (DD_MODEL == 0) {
			dd.biz.navigation.setMenu({
				backgroundColor: backgroundColor || "#ADD8E6",
				textColor: textColor || "#ADD8E611",
				items: items,
				onSuccess: res => {
					cb && cb(res);
				},
				onFail: err => console.error(err),
			});
		} else if (DD_MODEL == 1) {
			sinoware.biz.navigation.setMenu({
				backgroundColor: backgroundColor || "#ADD8E6",
				textColor: textColor || "#ADD8E611",
				items: items,
				onSuccess: res => {
					cb && cb(res);
				},
				onFail: err => console.error(err),
			});
		}
	},
	/**
	 * 扫码
	 * @param {*} type type 为 all、qrCode二维码、barCode条形码，默认是all。
	 * @returns  { 'text': String}
	 */
	scan: (type) => {
		return new Promise((resolve, reject) => {
			// 专属钉
			if (DD_MODEL == 0) {
				dd.biz.util.scan({
					type: type || "all",
					onSuccess: function(res) {
						let barcode = res.text;
						if (barcode.indexOf("许可证号") >= 0) {
							let start = barcode.indexOf("许可证号") + 5;
							console.log('获取的二维码 start：' + start);
							barcode = barcode.substring(start, start + 12);
							barcode = barcode.replace(/(^\s*)|(\s*$)/g, "");
							console.log('获取的二维码 licCode：' + barcode);
						}
						resolve(barcode);
					},
					onFail: err => reject(err),
				});
			} else if (DD_MODEL == 1) {
				sinoware.biz.util.scan({
					type: type || "all",
					onSuccess: function(res) {
						let barcode = res.text;
						if (barcode.indexOf("许可证号:") >= 0) {
							let start = barcode.indexOf("许可证号:") + 5;
							console.log('获取的二维码 start：' + start);
							barcode = barcode.substring(start, start + 12);
							barcode = barcode.replace(/(^\s*)|(\s*$)/g, "");
							console.log('获取的二维码 licCode：' + barcode);
						}
						resolve(barcode);
					},
					onFail: err => reject(err),
				});
			}
		});
	},
	/**
	 * 二维码扫码
	 * @returns
	 */
	qrCode: () => {
		return new Promise((resolve, reject) => {
			// 专属钉
			if (DD_MODEL == 0) {
				dd.biz.util.scan({
					type: "qrCode",
					onSuccess: function(res) {
						let barcode = res.text;
						if (barcode.indexOf("许可证号:") >= 0) {
							let start = barcode.indexOf("许可证号:") + 5;
							console.log('获取的二维码 start：' + start);
							barcode = barcode.substring(start, start + 12);
							barcode = barcode.replace(/(^\s*)|(\s*$)/g, "");
							console.log('获取的二维码 licCode：' + barcode);
						}
						resolve(barcode);
					},
					onFail: err => reject(err),
				});
			} else if (DD_MODEL == 1) {
				sinoware.biz.util.scan({
					type: "qrCode",
					onSuccess: function(res) {
						let barcode = res.text;
						if (barcode.indexOf("许可证号:") >= 0) {
							let start = barcode.indexOf("许可证号:") + 5;
							console.log('获取的二维码 start：' + start);
							barcode = barcode.substring(start, start + 12);
							barcode = barcode.replace(/(^\s*)|(\s*$)/g, "");
							console.log('获取的二维码 licCode：' + barcode);
						}
						resolve(barcode);
					},
					onFail: err => reject(err),
				});
			}
		});
	},
	/**
	 * 分享
	 * @returns
	 */
	shareContent(type, title, url, content) {
		if (content) {
			if (DD_MODEL == 0) {
				dd.biz.util.share({
					type: type, // 分享类型，0:全部组件 默认；1:只能分享到钉钉；2:不能分享，只有刷新按钮
					content: content,
					title: title,
					url: url,
					onSuccess: function() {},
					onFail: function() {},
				});
			} else if (DD_MODEL == 1) {
				sinoware.biz.util.share({
					type: type, // 分享类型，0:全部组件 默认；1:只能分享到钉钉；2:不能分享，只有刷新按钮
					content: content,
					url: url,
					title: title,
					onSuccess: function() {},
					onFail: function() {},
				});
			}

		} else {
			if (DD_MODEL == 0) {
				dd.biz.util.share({
					type: type, // 分享类型，0:全部组件 默认；1:只能分享到钉钉；2:不能分享，只有刷新按钮
					title: title,
					url: url,
					onSuccess: function() {},
					onFail: function() {},
				});
			} else if (DD_MODEL == 1) {
				sinoware.biz.util.share({
					type: type, // 分享类型，0:全部组件 默认；1:只能分享到钉钉；2:不能分享，只有刷新按钮
					url: url,
					title: title,
					onSuccess: function() {},
					onFail: function() {},
				});
			}
		}
	},
	/**
	 * 条形码扫码
	 * @returns
	 */
	barCode: () => {
		return new Promise((resolve, reject) => {
			// 专属钉
			if (DD_MODEL == 0) {
				dd.biz.util.scan({
					type: "barCode",
					onSuccess: function(res) {
						let barcode = res.text;
						if (barcode.indexOf("许可证号：") >= 0) {
							let start = barcode.indexOf("许可证号：") + 5;
							console.log('获取的二维码 start：' + start);
							barcode = barcode.substring(start, start + 13);
							barcode = barcode.replace(/(^\s*)|(\s*$)/g, "");
							console.log('获取的二维码 licCode：' + barcode);
						}
						resolve(barcode);
					},
					onFail: err => reject(err),
				});
			} else if (DD_MODEL == 1) {
				sinoware.biz.util.scan({
					type: "barCode",
					onSuccess: function(res) {
						let barcode = res.text;
						if (barcode.indexOf("许可证号：") >= 0) {
							let start = barcode.indexOf("许可证号：") + 5;
							console.log('获取的二维码 start：' + start);
							barcode = barcode.substring(start, start + 13);
							barcode = barcode.replace(/(^\s*)|(\s*$)/g, "");
							console.log('获取的二维码 licCode：' + barcode);
						}
						resolve(barcode);
					},
					onFail: err => reject(err),
				});
			}
		});
	},
	/**
	 * 拨打电话
	 * @param {*} phoneNum
	 */
	makePhoneCall(phoneNum) {
		// 专属钉
		if (DD_MODEL == 0) {
			dd.biz.telephone.showCallMenu({
				phoneNumber: phoneNum, // 期望拨打的电话号码
				code: '+86', // 国家代号，中国是+86
				showDingCall: true, // 是否显示钉钉电话
				onSuccess: function() {},
				onFail: function(e) {
					console.log(e, JSON.stringify(e))
				},
			});
		} else if (DD_MODEL == 1) {
			sinoware.biz.telephone.showCallMenu({
				phoneNumber: phoneNum, // 期望拨打的电话号码
				code: '+86', // 国家代号，中国是+86
				showDingCall: true, // 是否显示钉钉电话
				onSuccess: function() {},
				onFail: function(e) {
					console.log(e, JSON.stringify(e))
				},
			});
		}
	},
	/**
	 * 定位
	 * @returns
	 */
	geolocation() {
		return new Promise((resolve, reject) => {
			// 专属钉
			if (DD_MODEL == 0) {
				console.log('------')
				dd.device.geolocation.get({
					targetAccuracy: 200,
					coordinate: 1,
					withReGeocode: true,
					useCache: false, // 默认是true，如果需要频繁获取地理位置，请设置false
					onSuccess: function(result) {
						console.log('-----', result)
						resolve(result);
					},
					onFail: function(err) {
						console.log('err', err)
						reject(err)
					}
				});
				console.log('------')
				// 专有钉
			} else if (DD_MODEL == 1) {
				sinoware.device.geolocation.get({
					targetAccuracy: 200,
					coordinate: 1,
					withReGeocode: true,
					useCache: false, // 默认是true，如果需要频繁获取地理位置，请设置false
					onSuccess: function(result) {
						resolve(result);
					},
					onFail: err => reject(err),
				});
			}
		});
	},
	/**
	 * NFC读取
	 * @returns
	 */
	nfcReader() {
		return new Promise((resolve, reject) => {
			// 专属钉
			if (DD_MODEL == 0) {
				alert('开启识别NFC, 点击确定后, 用手机靠近NFC设备');
				dd.device.nfc.nfcRead({
					onSuccess: function(data) {
						resolve(data);
					},
					onFail: function(err) {
						if ((err["tagId"])) {
							let cardId = err["tagId"].replace(/:/g, '').toUpperCase();
							resolve(cardId);
						} else {
							reject(err['errorMessage']);
						}
					},
				});
			} else if (DD_MODEL == 1) {
				alert('开启识别NFC, 点击确定后, 用手机靠近NFC设备');
				sinoware.device.nfc.nfcRead({
					onSuccess: function(data) {
						resolve(data);
					},
					onFail: function(err) {
						if ((err["tagId"])) {
							let cardId = err["tagId"].replace(/:/g, '').toUpperCase();
							resolve(cardId);
						} else {
							reject(err['errorMessage']);
						}
					},
				});
			}
		});
	},

	nfcStop() {
		return new Promise((resolve, reject) => {
			dd.device.nfc.nfcStop();
		});
	},

	/**
	 * 打开指定位置
	 * @param {*} lat     纬度
	 * @param {*} long    经度
	 * @param {*} title   地址/POI名称
	 */
	navigateMap(lat, long, title) {
		// 专属钉
		if (DD_MODEL == 0) {
			dd.biz.map.view({
				latitude: lat,
				longitude: long,
				title: title,
			});
		} else if (DD_MODEL == 1) {
			sinoware.biz.map.view({
				latitude: lat,
				longitude: long,
				title: title,
			});
		}
	},
	/**
	 * 复制到剪切板
	 */
	clipboardData(text, callback) {
		// 专属钉
		if (DD_MODEL == 0) {
			dd.biz.clipboardData.setData({
				text: text,
				onSuccess: function(result) {
					callback(true)
				},
				onFail: function() {
					callback(false)
				},
			});
		} else if (DD_MODEL == 1) {
			sinoware.biz.clipboardData.setData({
				text: text,
				onSuccess: function(result) {
					callback(true)
				},
				onFail: function() {
					callback(false)
				},
			});
		}
	},
	/**
	 * 打开指定聊天页面
	 * @param {Object} userId
	 */
	openSingleChat(userId, callback) {
		// 专属钉
		if (DD_MODEL == 0) {
			dd.biz.chat.openSingleChat({
				corpId: 'dingcc3c8a50fc75c24dffe93478753d9884', // 企业id,必须是用户所属的企业的corpid
				userId: userId, // 用户的uerid
				onSuccess: function() {
					callback(true)
				},
				onFail: function() {
					callback(false)
				},
			})
		} else if (DD_MODEL == 1) {
			sinoware.biz.chat.openSingleChat({
			  corpId: 'dingcc3c8a50fc75c24dffe93478753d9884', // 企业id,必须是用户所属的企业的corpid
			  userId:userId, // 用户的uerid
			  onSuccess : function() { callback(true) },
			  onFail : function() { callback(false) },
			})
		}
	},
	/**
	 * 地图选点获取位置
	 */
	getLocationByMap(lat, lng, scope = 500) {
		return new Promise((resolve, reject) => {

			// 专属钉
			if (DD_MODEL == 0) {
				let obj = {};
				obj.latitude = lat; // 纬度，非必须
				obj.longitude = lng; // 经度，非必须
				obj.scope = scope;
				obj.onSuccess = function(result) {
					console.log('0------', result)
					resolve([result.latitude, result.longitude, ]);
				};
				obj.onFail = function(err) {
					console.log('err', err)
					reject(err);
				};
				dd.biz.map.locate(obj);
				// 专有钉
			} else if (DD_MODEL == 1) {
				let obj = {};
				if (lat != null && lat != '' && lat != undefined) {
					obj.latitude = lat; // 纬度，非必须
					obj.longitude = lng; // 经度，非必须
				}
				obj.scope = scope;
				obj.onSuccess = function(result) {
					resolve([result.latitude, result.longitude,]);
				};
				obj.onFail = function(err) {
					reject(err);
				};
				sinoware.biz.map.locate(obj);
			}
		});
	},

	/**
	 * 地图选点获取位置 带search
	 */
	getLocationInMapBySearch(lat, lng, scope = 500) {
		return new Promise((resolve, reject) => {

			// 专属钉
			if (DD_MODEL == 0) {
				let obj = {};
				if (lat != null && lat != '' && lat != undefined) {
					obj.latitude = lat; // 纬度，非必须
					obj.longitude = lng; // 经度，非必须
				}
				obj.scope = scope;
				obj.onSuccess = function(result) {
					resolve([result.latitude, result.longitude, ]);
				};
				obj.onFail = function(err) {
					reject(err);
				};
				dd.biz.map.search(obj);
			} else if (DD_MODEL == 1) {
				let obj = {};
				if (lat != null && lat != '' && lat != undefined) {
				  obj.latitude = lat; // 纬度，非必须
				  obj.longitude = lng; // 经度，非必须
				}
				obj.scope = scope;
				obj.onSuccess = function(result) {
				  resolve([result.latitude, result.longitude,]);
				};
				obj.onFail = function(err) {
				  reject(err);
				};
				sinoware.biz.map.search(obj);
			}
		});
	},

	/**
	 * 钉钉免登
	 * @param {*} agentId
	 * @returns
	 */
	ddLogin(agentId) {
		console.log('--====', DD_MODEL)
		return new Promise((resolve, reject) => {
			// 专属钉
			if (DD_MODEL == 0) {
				if (!agentId) {
					reject("缺失agentId");
				}
				anyPortal.ready({
						appId: agentId,
						jsApiList: [
							'device.base.getUUID', 'biz.util.openLink',
							'biz.navigation.close', 'device.notification.toast',
							'device.notification.alert', 'device.notification.confirm',
							'device.audio.startRecord', 'device.audio.stopRecord',
							'device.audio.onRecordEnd', 'device.audio.download',
							'device.audio.play', 'biz.util.previewImage', 'biz.navigation.setTitle',
							'biz.navigation.setRight', 'biz.navigation.setMenu',
							'biz.util.scan', 'biz.util.share', 'biz.telephone.showCallMenu',
							'device.geolocation.get', 'device.nfc.nfcRead',
							'biz.map.view', 'biz.clipboardData.setData',
							'biz.chat.openSingleChat', 'biz.map.locate',
							'biz.map.search', 'biz.util.openLink', 'biz.navigation.close',
							'device.notification.toast', 'device.notification.alert',
						],
					},
					function() {
						// 获取钉钉token
						anyPortal.requestAuthCode({
							onSuccess: function(token) {
								console.log('token', token)
								// 获取用户信息
								anyPortal.getAccountInfo(token.code, {
									onSuccess: function(userInfo) {
										if (Number(userInfo.code) === 996) {
											// 选择用户
											anyPortal.saveAppAccountRel({
												thirdPartyUuid: userInfo.msg,
												accountUuid: userInfo.data[0].accountUuid,
											}, {
												onSuccess: function(info) {
													console.log('info',info)
												},
												onFail: function(e) {
													console.log('e',e)
												},
											})
										} else {
											console.log('userInfo------',userInfo)
											resolve(userInfo)
										}
									},
									onFail: err => {
										console.log('err', err)
									},
								})
							},
							onFail: err => {
								console.log("fun.onFail:", "1111111")
								dd.device.geolocation.get({
									targetAccuracy: 200,
									coordinate: 1,
									withReGeocode: true,
									useCache: true, // 默认是true，如果需要频繁获取地理位置，请设置false
									onSuccess: function(result) {
										console.log("geolocation:", JSON.stringify(result))
									},
									onFail: function(err) {},
								});
							},
						});
					});
			} else if (DD_MODEL == 1) {
				if (!agentId) {
					alert("缺失agentId")
				}
				var jsApiLists = [
					'runtime.info', 'biz.contact.choose', 'runtime.getPasstoken',
					'device.nfc.nfcRead',
					'device.notification.confirm', 'device.notification.alert',
					'device.geolocation.get', 'device.nfc.nfcRead',
					'device.notification.prompt', 'biz.ding.post', 'biz.telephone.call',
					'biz.telephone.showCallMenu',
					'biz.util.openLink', 'biz.navigation', 'biz.util.uploadImage',
					'device.launcher.checkInstalledApps',
					'device.launcher.launchApp', 'biz.map.view', 'biz.map.locate','biz.map.search',
					'biz.util.ut', 'device.base.getUUID',
					'device.geolocation.start', 'device.geolocation.stop',
					'device.audio.onRecordEnd', 'device.audio.startRecord',
					'device.audio.stopRecord', 'device.audio.download', 'device.audio.play',
					'device.audio.pause',
					'device.audio.resume', 'device.audio.stop', 'device.audio.onPlayEnd',
					'biz.chat.openSingleChat','biz.clipboardData.setData','device.nfc.nfcWrite',
				];
				sinoware.ready({
				    agentId: agentId,
				    onSuccess: () => {
						//config：调用需要鉴权移动平台jsapi前，需要调用config进行鉴权
						//最佳实践：如果是vue这种单页应用，只需要在入口位置调用一次config，将所有用到的需要鉴权的api列表传入即可
				      sinoware.config({
						agentId: agentId,
						jsApiList:jsApiLists,
				        onSuccess: (data) => {
							console.log("sinoware.config:onSuccess--:",JSON.stringify(data))
							sinoware.runtime.permission.requestAuthCode({
								onSuccess: function (token) {
									//获取登录用户信息
									sinoware.runtime.getAccountInfo({
										agentId: agentId,
										onSuccess:function(data){
											
											sinoware.device.base.getUUID({
											  onSuccess: function(data) {
												console.log("getUUID（onSuccess）：",JSON.stringify(data))
											  },
											  onFail: function(err) {
												console.log("getUUID（onFail）：",JSON.stringify(err))
											  },
											});
											resolve(data);
										}
									});
									//进入页面加载数据
								},
								onFail: function (err) {
									console.log('requestAuthCode.fail:'+ JSON.stringify(err));
								}
							})
						}
				     })
					},
					onFail: function (err) {
						console.log('requestAuthCode.fail:'+ JSON.stringify(err));
					}
				})
				
				// sinoware.ready({
				// 	agentId: agentId,
				// 	jsApiList: [
				// 		'runtime.info', 'biz.contact.choose', 'runtime.getPasstoken',
				// 		'device.nfc.nfcRead',
				// 		'device.notification.confirm', 'device.notification.alert',
				// 		'device.geolocation.get', 'device.nfc.nfcRead',
				// 		'device.notification.prompt', 'biz.ding.post', 'biz.telephone.call',
				// 		'biz.telephone.showCallMenu',
				// 		'biz.util.openLink', 'biz.navigation', 'biz.util.uploadImage',
				// 		'device.launcher.checkInstalledApps',
				// 		'device.launcher.launchApp', 'biz.map.view', 'biz.map.locate','biz.map.search',
				// 		'biz.util.ut', 'device.base.getUUID',
				// 		'device.geolocation.start', 'device.geolocation.stop',
				// 		'device.audio.onRecordEnd', 'device.audio.startRecord',
				// 		'device.audio.stopRecord', 'device.audio.download', 'device.audio.play',
				// 		'device.audio.pause',
				// 		'device.audio.resume', 'device.audio.stop', 'device.audio.onPlayEnd',
				// 		'biz.chat.openSingleChat','biz.clipboardData.setData','device.nfc.nfcWrite',
				// 	],
				// 	onSuccess: () => {
				// 		sinoware.runtime.permission.requestAuthCode({
				// 			onSuccess: (token) => {
				// 				console.log('token', token)
				// 				sinoware.runtime.getAccountInfo({
				// 					onSuccess: data => {
				// 						console.log('data', data)
				// 						resolve(data);
				// 					},
				// 				})
				// 			},
				// 			onFail: (e) => {
				// 				console.log(e)
				// 			},
				// 		})
				// 	},
				// 	onFail: (err) => {
				// 		console.log('err', err)
				// 	},
				// });
			}
		});
	},

	/**
	 * 获取设备信息
	 * @returns Promise
	 */
	device() {
		return new Promise((resolve, reject) => {
			let deviceinfo = {
				model: "",
				platform: "DingDing",
				uuid: "",
				version: "",
				manufacturer: "",
				isVirtual: "",
				serial: "",
			};
			// DD_MODEL == 0 专属钉
			if (DD_MODEL == 0) {
				dd.device.base.getUUID({
					onSuccess: function(data) {
						deviceinfo.uuid = data["uuid"];
						dd.device.base.getPhoneInfo({
							onSuccess: function(data) {
								deviceinfo.model = data["model"];
								deviceinfo.version = data["version"];
								deviceinfo.manufacturer = data["brand"];
								deviceinfo.isVirtual = data["operatorType"];
								resolve(deviceinfo);
							},
							onFail: function(err) {
								reject(err);
							},
						});
					},
					onFail: function(err) {
						reject(err);
					},
				});
				// 专有钉
			} else if (DD_MODEL == 1) {
				sinoware.device.base.getUUID({
				  onSuccess: function(data) {
					console.log("getUUID（onSuccess）：",JSON.stringify(data))
				    deviceinfo.uuid = data["uuid"];
				    sinoware.device.base.getPhoneInfo({
				      onSuccess: function(data) {
				        deviceinfo.model = data["model"];
				        deviceinfo.version = data["version"];
				        deviceinfo.manufacturer = data["brand"];
				        deviceinfo.isVirtual = data["operatorType"];
						console.log("getPhoneInfo（onSuccess）：",JSON.stringify(data))
				        resolve(deviceinfo);
				      },
				      onFail: function(err) {
						console.log("getPhoneInfo（onFail）：",JSON.stringify(err))
				        reject(err);
				      },
				    });
				  },
				  onFail: function(err) {
					console.log("getUUID（onFail）：",JSON.stringify(err))
				    reject(err);
				  },
				});
			}
		});
	},

	/**
	 * 图片旋转角度
	 */
	changeImgOrientation(resImg, Orientation) {
		return new Promise((resolve, reject) => {
			let self = this;
			let img = new Image();
			img.src = resImg;
			img.onload = function() {
				let canvas = document.createElement("canvas");
				let ctx = canvas.getContext("2d");
				let imgWidth = canvas.width = this.width;
				let imgHeight = canvas.height = this.height;
				// 如果方向角不为1，都需要进行旋转 added by lzk
				if (Orientation && Orientation != 1) {
					switch (Orientation) {
						case 6: // 旋转90度
							canvas.width = this.height;
							canvas.height = this.width;
							ctx.rotate(Math.PI / 2);
							ctx.drawImage(this, 0, -imgHeight, imgWidth, imgHeight);
							break;
						case 3: // 旋转180度
							ctx.rotate(Math.PI);
							ctx.drawImage(this, -imgWidth, -imgHeight, imgWidth, imgHeight);
							break;
						case 8: // 旋转-90度
							canvas.width = imgHeight;
							canvas.height = imgWidth;
							ctx.rotate(3 * Math.PI / 2);
							ctx.drawImage(this, -imgWidth, 0, imgWidth, imgHeight);
							break;
					}
				} else {
					ctx.drawImage(this, 0, 0, imgWidth, imgHeight);
				}
				let base64code = canvas.toDataURL("image/jpeg");
				resolve(base64code);
			}
		})
	},
	/**
	 * 从本地相册选择图片或使用相机拍照
	 * @param {Object} maxSize 最多可以选择的图片张数，默认   1
	 * @param {Int} sType 0 默认，1 相册 ， 2 拍照
	 * @param {Number} quality   0-1
	 * @param {Number} widthScale 0-1
	 * @param {String} enableVide 'false'
	 */
	chooseImageToCompress({
	  maxSize = 1,
	  sType = 0,
	  quality = 0.65,
	  widthScale = 1,
	}) {
	  return new Promise((resolve, reject) => {
	    let ar = ['album', 'camera',];
	    if (sType == 1) {
	      ar = ['album',];
	    } else if (sType == 2) {
	      ar = ['camera',];
	    }
	    uni.chooseImage({
	      count: maxSize,
	      sizeType: ['original', 'compressed',],
	      sourceType: ar,
	      success: res1 => {
	        uni.showLoading({
	          title: "正在压缩图片...",
	          success() {},
	          mask: false,
	        });
	        Promise.all(res1.tempFilePaths.map(path => {
	          return new Promise((resolve, reject) => {
	            let self = this;
	            let img = new Image();
	            let canvas = document.createElement("canvas");
	            let ctx = canvas.getContext("2d");
	            img.src = path;
	            img.onload = function(){
	              EXIF.getData(img, function() {
	                let Orientation = EXIF.getTag(this, 'Orientation');
	                let make = EXIF.getTag(this, 'Make');
	                // IOS 13.4以上不需要进行旋转
	                let getVersionRotate = ()  => {
	                  let ua = navigator.userAgent.toLowerCase();
	                  let ver = ua.match(/cpu iphone os (.*?) like mac os/);
	                  try{
	                    let b = ver[1].replace(/_/g,".");
	                    return self.toNum(b) >= self.toNum(13.4);
	                  }catch(err){
	                    console.log(err);
	                    return false;
	                  }
	                  
	                };
	
	                if(Orientation && Orientation != 1 && !getVersionRotate()){
	                  // 当旋转值存在且不为1时，调用changeImgOrientation将其还原，并返回base64值
	                  self.changeImgOrientation(path,Orientation).then(rxp => {
	                    let imgXp = new Image();
	                    imgXp.src = rxp;
	                    imgXp.onload = function(){
	                      canvas.width = imgXp.width;
	                      canvas.height = imgXp.height;
	                      ctx.drawImage(img, 0, 0, imgXp.width, imgXp.height);
	                      let tmp = canvas.toDataURL('image/jpeg');
	                      let dp = {
	                        graphicContents: tmp.split(',')[1],
	                        size:null,
	                      };
	                      self.getImgByteSize(dp);
	                      if(dp.size >= (4 * 1024 * 1024)){ // 大于4M
	                        quality = 0.50;
	                        widthScale = 0.6;
	                      }else if(dp.size >= (3 * 1024 * 1024) && dp.size <= (1024 * 1024 * 4)){ // 大于3M
	                        quality = 0.60;
	                        widthScale = 0.7;
	                      }else if(dp.size >= (1024 * 1024) && dp.size < (1024 * 1024 * 3)){ // 大于1M 小于3M
	                        quality = 0.70;
	                        widthScale = 0.8;
	                      }else{  // 小于1M
	                        quality = 0.92;
	                        widthScale = 0.9;
	                      }
	                      if(make != 'Apple'){
	                        widthScale = 0.7;
	                      }
	                      self.compressImage(rxp, path.substring(path.lastIndexOf('.') + 1), maxSize, quality,widthScale, make == 'Apple').then(rpp => {
	                        resolve(rpp);
	                      });
	                    };
	                  });
	                }else{
	                  canvas.width = img.width;
	                  canvas.height = img.height;
	                  ctx.drawImage(img, 0, 0, img.width, img.height);
	                  let tmp = canvas.toDataURL('image/jpeg');
	                  let dp = {
	                    graphicContents: tmp.split(',')[1],
	                    size:null,
	                  };
	                  self.getImgByteSize(dp);
	                  if(dp.size >= (4 * 1024 * 1024)){ // 大于4M
	                    quality = 0.50;
	                    widthScale = 0.6;
	                  }else if(dp.size >= (3 * 1024 * 1024) && dp.size <= (1024 * 1024 * 4)){ // 大于3M
	                    quality = 0.60;
	                    widthScale = 0.7;
	                  }else if(dp.size >= (1024 * 1024) && dp.size < (1024 * 1024 * 3)){ // 大于1M 小于3M
	                    quality = 0.70;
	                    widthScale = 0.8;
	                  }else{  // 小于1M
	                    quality = 0.92;
	                    widthScale = 0.9;
	                  }
	                  if(make != 'Apple'){
	                    widthScale = 0.7;
	                  }
	                  self.compressImage(path, path.substring(path.lastIndexOf('.') + 1), maxSize, quality,widthScale, make == 'Apple').then(rpp => {
	                    resolve(rpp);
	                  });
	                }
	              })
	            };
	          });
	        })).then(resp => {
	          uni.hideLoading();
	          resolve(resp);
	        });
	      },
	      fail: err => {
	        uni.hideLoading();
	        reject();
	      },
	    });
	  });
	},

	toNum(a) {
		a = a.toString();
		let c = a.split('.');
		let num_place = ["", "0", "00", "000", "0000", ];
		let r = num_place.reverse();
		for (let i = 0; i < c.length; i++) {
			let len = c[i].length;
			c[i] = r[len] + c[i];
		}
		let res = c.join('');
		return res;
	},

	getImgByteSize(data) {
		if (data && data.graphicContents) { // 获取base64图片byte大小
			const equalIndex = data.graphicContents.indexOf('='); // 获取=号下标
			if (equalIndex > 0) {
				const str = data.graphicContents.substring(0, equalIndex); // 去除=号
				data.size = str.length;
			} else {
				const strLength = data.graphicContents.length;
				data.size = strLength;
			}
		} else {
			data.size = null;
		}
	},

	/**
	 * 图片压缩
	 */
	compressImage(file, fileExtra, num, quality = 0.3, widthScale = 0.8, isApple = false) {
		return new Promise((resolve, reject) => {
			let img = new Image();
			img.src = file;
			img.onload = function() {
				let newBase64 = ImageScale.compressImage(img, {
					// 压缩质量
					quality: quality,
					mime: 'image/jpeg',
					// 压缩时的放大系数，默认为1，如果增大，代表图像的尺寸会变大(最大不会超过原图)
					compressScaleRatio: 1,
					// ios的iPhone下主动放大一定系数以解决分辨率过小的模糊问题
					iphoneFixedRatio: 1,
					// 是否采用原图像素（不会改变大小）
					isUseOriginSize: false,
					// 增加最大宽度，增加后最大不会超过这个宽度
					maxWidth: 0,
					// 使用强制的宽度，如果使用，其它宽高比系数都会失效，默认整图使用这个宽度
					forceWidth: img.width * widthScale,
					// 同上，但是一般不建议设置，因为很可能会改变宽高比导致拉升，特殊场景下使用
					forceHeight: 0,
				});
				resolve(newBase64);
			}
		});
	},

	/**
	 * 功能埋点
	 * @param {*} info 埋点信息，例如：“点击发给我的”
	 */
	buriedPointFunction(info) {
		typeof anyware !== 'undefined' && anyware.util.addFunAccessLog({
			account: info,
		});
	},
	/**
	 * 业务埋点
	 * @param {*} operateDesc 操作描述， 如：零售户走访
	 * @param {*} operateInfo 操作内容， 如：零售户许可证编号
	 * @param {*} beganTime   操作开始时间(可选项)
	 */
	buriedPointBusiness(operateDesc, operateInfo, beganTime) {
		try {
			dd.device.geolocation.get({
				targetAccuracy: 200, // 期望定位精度半径（单位米）
				coordinate: 1, // 1：获取高德坐标， 0：获取标准坐标
				withReGeocode: true, // 是否需要带有逆地理编码信息
				useCache: true, // 默认是true，如果需要频繁获取地理位置，请设置false
				onSuccess: function(result) {
					let option = {
						account: operateDesc, // 操作描述
						content: operateInfo, // 内容，如：零售户许可证编号
						begTime: beganTime || new Date(), // 操作开始时间
						aalX: result['latitude'], // 坐标纬度
						aalY: result['longitude'], // 坐标经度
					};
					anyware.util.addBizAccessLog(option);
				},
				onFail: function(err) {
					console.error(err);
				},
			});
		} catch (error) {
			console.error("业务埋点失败", error);
		}
	},

	openLink(url) {
		return new Promise((resolve, reject) => {
			if (DD_MODEL == 0) {
				dd.biz.util.openLink({
					url: url,
					onSuccess: function(result) {
						resolve(result)
					},
					onFail: function(err) {
						reject(err)
					},
				});
			} else if (DD_MODEL == 1) {
				sinoware.biz.util.openLink({
					url: url,
					onSuccess: function(result) {
						resolve(result)
					},
					onFail: function(err) {
						reject(err)
					},
				});
			}
		})
	},

	closeWindow() {
		// DD_MODEL === 0 专属钉
		if (DD_MODEL == 0) {
			dd.biz.navigation.close({
				onSuccess: function(result) {
					console.log(result);
				},
				onFail: function(err) {
					console.log(err)
				},
			})
		} else if (DD_MODEL == 1) {
			sinoware.biz.navigation.close({
				onSuccess: function(result) {
					console.log(result);
				},
				onFail: function(err) {
					console.log(err)
				},
			})
		}

	},
}

export default DingDing;